'use strict';
const {getDefaultModelConfig} = require("../../utils/common");
const {parseNum} = require("../../utils");

module.exports = app => {
    const { STRING, INTEGER, DATE, BIGINT, DECIMAL } = app.Sequelize;
    const User = app.model.define(
        'User',
        {
            id: { type: BIGINT, primaryKey: true, autoIncrement: true },
            openid: STRING(255),
            phone: STRING(255),
            password: STRING(255),
            nickname: STRING(255),
            avatar_url: STRING(255),
            balance: {type: DECIMAL(10, 2), defaultValue: 0.00,
                get() {
                    return parseNum(this.getDataValue('balance'))
                },
            },
            status: {type: INTEGER, defaultValue: 1},
            parent_user_id: BIGINT(20),
            invite_qr_code: STRING(255),
            user_type: {
                type: INTEGER,
                defaultValue: 1, // 1 普通用户 2 商家 3 一级分销商 4 二级分销商
            },
            ...getDefaultModelConfig(app)
        },
        {
            tableName: 'user',
            timestamps: true,
            createdAt: 'create_time',
            updatedAt: 'update_time'
        }
    );
    // 关联
    User.associate = function () {
        // 关联上级
        app.model.Business.User.belongsTo(app.model.Business.User, {as: 'parent', foreignKey: 'parent_user_id'});
        // 账户余额记录
        app.model.Business.User.hasMany(app.model.Business.BalanceRecord, {as: 'balanceRecord', foreignKey: 'user_id'});
    }
    return User
};
